package pl.edu.agh.dosgi.logging.listener;

import java.util.HashMap;

import org.osgi.service.log.LogEntry;
import org.osgi.service.log.LogListener;
import org.osgi.service.log.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogbackListener implements LogListener {
	HashMap<Long, Logger> loggers = new HashMap<Long, Logger>();

	public void logged(LogEntry log) {
		if ((log.getBundle() == null) || (log.getBundle().getSymbolicName() == null)) {
			return;
		}

		Logger logger = loggers.get(log.getBundle().getBundleId());
		if (logger == null) {
			logger = LoggerFactory.getLogger(log.getBundle().getSymbolicName());
			loggers.put(log.getBundle().getBundleId(), logger);
		}

		if (log.getException() != null) {
			switch (log.getLevel()) {
			case LogService.LOG_DEBUG:
				logger.debug(log.getMessage(), log.getException());
				break;
			case LogService.LOG_INFO:
				logger.info(log.getMessage(), log.getException());
				break;
			case LogService.LOG_WARNING:
				logger.warn(log.getMessage(), log.getException());
				break;
			case LogService.LOG_ERROR:
				logger.error(log.getMessage(), log.getException());
				break;
			}
		} else {
			switch (log.getLevel()) {
			case LogService.LOG_DEBUG:
				logger.debug(log.getMessage());
				break;
			case LogService.LOG_INFO:
				logger.info(log.getMessage());
				break;
			case LogService.LOG_WARNING:
				logger.warn(log.getMessage());
				break;
			case LogService.LOG_ERROR:
				logger.error(log.getMessage());
				break;
			}
		}
	}
}